package simulator.entities;

import java.awt.Graphics;

import simulator.drawengine.Drawable;
import simulator.enums.LightState;
import simulator.enums.Loop;
import simulator.jsoncode.JSONEncoder;
import simulator.main.Simulator;
import simulator.types.Lane;
import simulator.types.Vector2f;

public class TrafficLane implements Drawable
{
	Simulator			_parent;

	Lane				_lane;
	BaseTrafficlight	_light;

	BaseVehicle			_lastVehicle	= null;

	Vector2f			_spawnPosition;
	float				_spawnHeading;
	Vector2f			_farLoopPosition;
	Vector2f			_nearLoopPosition;
	Vector2f			_holdPosition;
	Vector2f			_lightPosition;

	public TrafficLane(Simulator s, Lane lane, BaseTrafficlight light, Vector2f spawnPos, float spawnHeading, Vector2f farLoopPos, Vector2f nearLoopPos, Vector2f holdPos, Vector2f lightPos)
	{
		_parent = s;

		_lane = lane;
		_light = light;
		
		_spawnPosition = spawnPos;
		_spawnHeading = spawnHeading;
		_farLoopPosition = farLoopPos;
		_nearLoopPosition= nearLoopPos;
		_holdPosition = holdPos;
		_lightPosition = lightPos;
	}

	public void setLightState(LightState s)
	{
		_light.setState(s);
	}

	public void nearLoopEntered(BaseVehicle veh)
	{
		String msg = JSONEncoder.getLoopEvent(_lane, veh.getType(), Loop.NEAR, false, veh._destinationLane._lane);
		_parent.TCPsend(msg);
	}

	public void nearLoopExited(BaseVehicle veh)
	{
		String msg = JSONEncoder.getLoopEvent(_lane, veh.getType(), Loop.NEAR, true, veh._destinationLane._lane);
		_parent.TCPsend(msg);
	}

	public void farLoopEntered(BaseVehicle veh)
	{
		String msg = JSONEncoder.getLoopEvent(_lane, veh.getType(), Loop.FAR, false, veh._destinationLane._lane);
		_parent.TCPsend(msg);
	}

	public void farLoopExited(BaseVehicle veh)
	{
		String msg = JSONEncoder.getLoopEvent(_lane, veh.getType(), Loop.FAR, true, veh._destinationLane._lane);
		_parent.TCPsend(msg);
	}

	public Lane getLane()
	{
		return _lane;
	}

	public void newVehicle(BaseVehicle veh)
	{
		if (_lastVehicle == null)
		{
			veh._front = null;
		}
		else
		{
			if (_lastVehicle._onApproach)
				veh._front = _lastVehicle;
			else
				veh._front = null;
		}

		_lastVehicle = veh;
	}

	@Override
	public void draw(Graphics g)
	{
		_light.onDraw(g, _lightPosition, _lane.getDirection());
	}
}